package day18;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo4 {
    Object data;
    ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();

    public void read(){
        String name = Thread.currentThread().getName();
        rwlock.readLock().lock();//获取读锁
//        lock.lock();
//        lock.unlock();
        try {
            System.out.println(name + "开始写入2s数据"+data);
            Thread.sleep(2000);
            System.out.println(name + "开始结束2s数据"+data);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            rwlock.readLock().unlock();//释放锁
        }
    }

    public void write(Object data){
        String name = Thread.currentThread().getName();
        rwlock.writeLock().lock();//获取读锁
        try {
            System.out.println(name + "开始写入2s数据"+data);
            Thread.sleep(2000);
            System.out.println(name + "开始结束2s数据"+data);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            rwlock.writeLock().unlock();//释放锁
        }
    }

    public static void main(String[] args) {
        Demo4 demo4 = new Demo4();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    demo4.read();
                }
            },"读"+i).start();
            for (int n = 0; n < 5; n++) {
                new Thread(() -> {
                    for (int j = 0; j < 5; j++) {
                        demo4.write(Math.random());
                    }
                },"写"+n).start();
            }
        }
    }
}
